package com.fashion.web.actions.management.brand;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.stereotype.Controller;

import com.fashion.model.NewsColumn;
import com.fashion.model.brand.Brand;
import com.fashion.service.ColumnService;
import com.fashion.service.brand.BrandService;
import com.fashion.utils.ColumnTree;
import com.fashion.utils.StringUtils;
import com.opensymphony.xwork2.ActionSupport;

@Controller
@ParentPackage("json-default")
@Namespace("/management/brand")
public class BrandAdminAction extends ActionSupport {
	public static Logger LOGGER = Logger.getLogger(BrandAdminAction.class);
	
	public static final String LOGO_FOLDER = "/brand/logo/";
	public static final String FIGURE_IMAGE_FOLDER = "/brand/figure/";
	private Map result = new HashMap();
	private String findPattern = "FIRST_CHAR";
	private String firstChar = "a";
	private String enTitle;
	private Brand brandForm = new Brand();
	private String industryIds;
	private File uploadify;
	private String uploadifyFileName;
	@Resource(name = "brandService")
	private BrandService brandService;
	@Resource(name = "columnService")
	private ColumnService columnService;
	private int rows;
	private int page;
	private List<ColumnTree> industryTrees;
	private List<ColumnTree> districtTrees;
	
	@Action(value = "fetch_industries", results = {@Result(name = SUCCESS, type = "json", params = {"root", "industryTrees"})})
    public String fetchIndustriesForTree() throws Exception {
		List<NewsColumn> columns = columnService.findAllTreeColumns();
		for(NewsColumn column : columns){
			if("brand".equals(column.getUrl())){
				industryTrees = columnService.convertToTrees(column.getChildrenColumns());
			}
		}
        return SUCCESS;
    }
	
	@Action(value = "fetch_districts", results = {@Result(name = SUCCESS, type = "json", params = {"root", "districtTrees"})})
    public String fetchDistrictsForTree() throws Exception {
		List<NewsColumn> columns = columnService.findAllTreeColumns();
		for(NewsColumn column : columns){
			if("district".equals(column.getUrl())){
				districtTrees = columnService.convertToTrees(column.getChildrenColumns());
			}
		}
        return SUCCESS;
    }
	
	@Action(value = "find_brands", results = { @Result(name = SUCCESS, type = "json", params = {
			"root", "result" }) })
	public String find() throws Exception {
		if("EN_TITLE".equals(findPattern)){	
			long total = 0;
			List<Brand> brands;
			total = brandService.countByEnTitle(enTitle);
			brands = brandService.findByEnTitle(enTitle, rows
					* (page - 1), rows);
			result.put("total", total);
			result.put("rows", brands);
		}else{
			long total = 0;
			List<Brand> brands;
			if("others".equals(firstChar)){
				total = brandService.countNotStartWithEn();
				brands = brandService.findNotStartWithEn(rows
						* (page - 1), rows);
				
			}else{
				total = brandService.countByFirstChar(firstChar);
				brands = brandService.findByFirstChar(firstChar, rows
						* (page - 1), rows);			
			}
			result.put("total", total);
			result.put("rows", brands);
		}
		return SUCCESS;
	}

	@Action(value = "brand_index", results = { @Result(name = SUCCESS, location = "brand.jsp") })
	public String index() throws Exception {
		return SUCCESS;
	}
	
	@Action(value = "delete_brand", results = { @Result(name = SUCCESS, location = "brand.jsp") })
	public String deleteBrand() throws Exception {
		brandService.delete(brandForm);
		return SUCCESS;
	}

	@Action(value = "add_brand", results = { @Result(name = SUCCESS, location = "brand_form.jsp") })
	public String addBrand() throws Exception {
		return SUCCESS;
	}

	@Action(value = "update_brand", results = { @Result(name = SUCCESS, location = "brand_form.jsp") })
	public String updateBrand() throws Exception {
		brandForm = brandService.findById(brandForm.getId());
		List<NewsColumn> industries = brandForm.getIndustries();
		for(NewsColumn industry : industries){
			if(industryIds == null || "".equals(industryIds)){
				industryIds = industry.getId();
			}else{
				industryIds = industryIds + "," + industry.getId();
			}		
		}
		return SUCCESS;
	}

	@Action(value = "add_or_update_brand", results = { @Result(name = SUCCESS, location = "brand.jsp") })
	public String addUpdateBrand() throws Exception {
		LOGGER.info("*********1" + industryIds);
		String[] brandColumnIds = industryIds.split(",");
		List<NewsColumn> columns = columnService.findColumns(brandColumnIds);
		LOGGER.info("*********2" + columns.size());
		brandForm.setIndustries(columns);
		LOGGER.info("*********3" + brandForm.getId());
		if (brandForm.getId() == null || brandForm.getId().equals("")) {
			brandService.add(brandForm);
		} else {
			brandService.update(brandForm);
		}
		LOGGER.info("*********4" );
		return SUCCESS;
	}

	@Action(value = "add_logo", results = { @Result(name = SUCCESS, type = "json", params = {
			"root", "brandForm.logo" }) })
	public String addLogo() {
		LOGGER.debug("addLogo");
		
		String destPath = "";
		String folder = ServletActionContext.getServletContext()
				.getRealPath(LOGO_FOLDER);
		if (brandForm.getId() != null && !brandForm.getId().equals("")) {
			brandForm = brandService.findById(brandForm.getId());
			String oldLogo = brandForm.getLogo();
			if (oldLogo != null && !"".equals(oldLogo)) {
				// delete old one
				String oldPath = folder + File.separator + brandForm.getLogo();
				File old = new File(oldPath);
				old.delete();
				destPath = oldPath;
			}
		}
		if("".equals(destPath)){
			String extName = "";
			if (uploadifyFileName.lastIndexOf(".") >= 0) {
				extName = uploadifyFileName.substring(uploadifyFileName.lastIndexOf("."));
			}
			String fileName = StringUtils.createTimeStamp() + extName;
			destPath = folder + File.separator + fileName;
			brandForm.setLogo(fileName);
		}
		File dest = new File(destPath);
		LOGGER.debug("New logo will be moved to " + destPath);
		try {
			FileUtils.copyFile(uploadify, dest);
		} catch (IOException e) {
			LOGGER.error(e);
		}
		LOGGER.debug("New logo has be moved to " + destPath);
		return SUCCESS;
	}
	
	@Action(value = "add_figure_image", results = { @Result(name = SUCCESS, type = "json", params = {
			"root", "brandForm.figureImage" }) })
	public String addFigureImage() {
		LOGGER.debug("addFigureImage");
		
		String destPath = "";
		String folder = ServletActionContext.getServletContext()
				.getRealPath(FIGURE_IMAGE_FOLDER);
		if (brandForm.getId() != null && !brandForm.getId().equals("")) {
			brandForm = brandService.findById(brandForm.getId());
			String oldFigureImage = brandForm.getFigureImage();
			if (oldFigureImage != null && !"".equals(oldFigureImage)) {
				// delete old one
				String oldPath = folder + File.separator + brandForm.getFigureImage();
				File old = new File(oldPath);
				old.delete();
				destPath = oldPath;
			}
		}
		if("".equals(destPath)){
			String extName = "";
			if (uploadifyFileName.lastIndexOf(".") >= 0) {
				extName = uploadifyFileName.substring(uploadifyFileName.lastIndexOf("."));
			}
			String fileName = StringUtils.createTimeStamp() + extName;
			destPath = folder + File.separator + fileName;
			brandForm.setFigureImage(fileName);
		}
		File dest = new File(destPath);
		LOGGER.debug("New logo will be moved to " + destPath);
		try {
			FileUtils.copyFile(uploadify, dest);
		} catch (IOException e) {
			LOGGER.error(e);
		}
		LOGGER.debug("New figure image has be moved to " + destPath);
		return SUCCESS;
	}

	@Action(value = "columnForm", results = { @Result(name = SUCCESS, location = "../../form_result.jsp") })
	public String add() {
		brandService.add(brandForm);
		return SUCCESS;
	}

	public Map getResult() {
		return result;
	}

	public void setFirstChar(String firstChar) {
		this.firstChar = firstChar;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public Brand getBrandForm() {
		return brandForm;
	}

	public void setBrandForm(Brand brandForm) {
		this.brandForm = brandForm;
	}

	public String getFirstChar() {
		return firstChar;
	}

	public void setUploadify(File uploadify) {
		this.uploadify = uploadify;
	}

	public void setUploadifyFileName(String uploadifyFileName) {
		this.uploadifyFileName = uploadifyFileName;
	}

	public String getEnTitle() {
		return enTitle;
	}

	public void setEnTitle(String enTitle) {
		this.enTitle = enTitle;
	}

	public String getFindPattern() {
		return findPattern;
	}

	public void setFindPattern(String findPattern) {
		this.findPattern = findPattern;
	}

	public List<ColumnTree> getIndustryTrees() {
		return industryTrees;
	}

	public String getIndustryIds() {
		return industryIds;
	}

	public void setIndustryIds(String industryIds) {
		this.industryIds = industryIds;
	}

	public List<ColumnTree> getDistrictTrees() {
		return districtTrees;
	}	
}